/*
 * Copyright 2009-2010 the original author or authors.
 *
 * Licensed under the Apache license, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.internna.iwebjtracker.administration;

import java.util.List;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Random;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.internna.iwebmvc.dao.DAO;
import org.internna.iwebmvc.model.Poll;
import org.internna.iwebmvc.utils.Assert;
import org.internna.iwebmvc.utils.CollectionUtils;

/**
 * Stores all active polls in the application.
 *
 * @author Jose Noheda
 * @since 1.0
 */
@Aspect
public final class PollManager {

    private static final Log logger = LogFactory.getLog(PollManager.class);

    private final DAO dao;
    private final Random random;
    private final List<Poll> polls;

    /**
     * Builds the bean and automatically generates the proxies for the intercepted classes.
     *
     * @param dao a non null instance
     */
    public PollManager(DAO dao) {
        Assert.notNull(dao);
        this.dao = dao;
        random = new Random();
        polls = new ArrayList<Poll>();
        refresh();
    }

    /**
     * Obtains all active polls in the system.
     *
     * @return a non null non modifiable collection
     */
    public Collection<Poll> getPolls() {
        return Collections.unmodifiableCollection(polls);
    }

    /**
     * Gets a poll at random from the active ones.
     *
     * @return any
     */
    public Poll getPoll() {
        if (CollectionUtils.isNotEmpty(polls)) {
            return polls.get(random.nextInt(polls.size()));
        }
        return null;
    }

    /**
     * Loads all active polls by request.
     *
     */
    public synchronized void refresh()  {
        polls.clear();
        List<Poll> loaded = dao.findByNamedQuery(Poll.FIND_ACTIVE_POLLS, 0, 9999, null);
        if (CollectionUtils.isNotEmpty(loaded)) {
            if (logger.isDebugEnabled()) {
                logger.debug("Loaded [" + loaded.size() + "] active polls from database");
            }
            polls.addAll(loaded);
        }
    }

    /**
     * Aspect to execute when a poll is added or toggle to active or inactive.
     *
     * @param retVal the result of the intercepted method
     */
    @AfterReturning(pointcut = "execution(* org.internna.iwebjtracker.services.Administrator.*Poll(..))", returning = "retVal")
    public void refreshOnPollCreation(Object retVal) {
        if (retVal == null) {
            refresh();
        }
    }

}
